package com.ruoyi.wms.service.impl;

import java.util.List;
import java.math.BigDecimal;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.wms.mapper.WmsReceiptOrderMapper;
import com.ruoyi.wms.mapper.WmsReceiptOrderDetailMapper;
import com.ruoyi.wms.domain.WmsReceiptOrder;
import com.ruoyi.wms.domain.WmsReceiptOrderDetail;
import com.ruoyi.wms.service.IWmsReceiptOrderService;
import com.ruoyi.wms.service.IWmsOwnerOrderNumberRuleService;
import com.ruoyi.wms.service.IWmsItemService;
import com.ruoyi.wms.service.IWmsInventoryService;
import com.ruoyi.wms.service.IWmsLocationService;
import com.ruoyi.wms.domain.WmsItem;
import com.ruoyi.wms.domain.WmsInventory;
import com.ruoyi.wms.domain.WmsLocation;
import com.ruoyi.wms.domain.dto.InventoryIncreaseRequest;
import com.ruoyi.wms.domain.dto.InventoryIncreaseResponse;
import java.util.ArrayList;

/**
 * 收货订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class WmsReceiptOrderServiceImpl implements IWmsReceiptOrderService 
{
    @Autowired
    private WmsReceiptOrderMapper wmsReceiptOrderMapper;

    @Autowired
    private WmsReceiptOrderDetailMapper wmsReceiptOrderDetailMapper;

    @Autowired
    private IWmsOwnerOrderNumberRuleService orderNumberRuleService;

    @Autowired
    private IWmsItemService wmsItemService;

    @Autowired
    private IWmsInventoryService wmsInventoryService;

    @Autowired
    private IWmsLocationService wmsLocationService;

    /**
     * 查询收货订单
     * 
     * @param orderId 收货订单主键
     * @return 收货订单
     */
    @Override
    public WmsReceiptOrder selectWmsReceiptOrderById(Long orderId)
    {
        WmsReceiptOrder order = wmsReceiptOrderMapper.selectWmsReceiptOrderById(orderId);
        if (order != null && StringUtils.isNotEmpty(order.getOrderNo()))
        {
            List<WmsReceiptOrderDetail> details = wmsReceiptOrderDetailMapper.selectWmsReceiptOrderDetailByOrderNo(order.getOrderNo());
            order.setDetailList(details);
        }
        return order;
    }

    /**
     * 根据订单编号查询收货订单
     * 
     * @param orderNo 订单编号
     * @return 收货订单
     */
    @Override
    public WmsReceiptOrder selectWmsReceiptOrderByOrderNo(String orderNo)
    {
        WmsReceiptOrder order = wmsReceiptOrderMapper.selectWmsReceiptOrderByOrderNo(orderNo);
        if (order != null)
        {
            List<WmsReceiptOrderDetail> details = wmsReceiptOrderDetailMapper.selectWmsReceiptOrderDetailByOrderNo(orderNo);
            order.setDetailList(details);
        }
        return order;
    }

    /**
     * 查询收货订单列表
     * 
     * @param wmsReceiptOrder 收货订单
     * @return 收货订单
     */
    @Override
    public List<WmsReceiptOrder> selectWmsReceiptOrderList(WmsReceiptOrder wmsReceiptOrder)
    {
        // 设置租户ID
        wmsReceiptOrder.setTenantId(SecurityUtils.getTenantId());
        return wmsReceiptOrderMapper.selectWmsReceiptOrderList(wmsReceiptOrder);
    }

    /**
     * 新增收货订单
     * 
     * @param wmsReceiptOrder 收货订单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWmsReceiptOrder(WmsReceiptOrder wmsReceiptOrder)
    {
        // 设置租户ID和创建信息
        wmsReceiptOrder.setTenantId(SecurityUtils.getTenantId());
        wmsReceiptOrder.setCreateBy(SecurityUtils.getUsername());
        wmsReceiptOrder.setCreateTime(DateUtils.getNowDate());
        
        int rows = wmsReceiptOrderMapper.insertWmsReceiptOrder(wmsReceiptOrder);
        insertWmsReceiptOrderDetail(wmsReceiptOrder);
        
        return rows;
    }

    /**
     * 修改收货订单
     * 
     * @param wmsReceiptOrder 收货订单
     * @return 结果
     */
    @Override
    @Transactional
    public int updateWmsReceiptOrder(WmsReceiptOrder wmsReceiptOrder)
    {
        wmsReceiptOrder.setUpdateBy(SecurityUtils.getUsername());
        wmsReceiptOrder.setUpdateTime(DateUtils.getNowDate());
        
        int deleteResult = wmsReceiptOrderMapper.deleteWmsReceiptOrderDetailByOrderNo(wmsReceiptOrder.getOrderNo());
        if (deleteResult < 0) {
            throw new RuntimeException("删除原有明细失败");
        }
        insertWmsReceiptOrderDetail(wmsReceiptOrder);
        int result = wmsReceiptOrderMapper.updateWmsReceiptOrder(wmsReceiptOrder);
        
        return result;
    }

    /**
     * 批量删除收货订单
     * 
     * @param orderIds 需要删除的收货订单主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteWmsReceiptOrderByIds(Long[] orderIds)
    {
        for (Long orderId : orderIds)
        {
            WmsReceiptOrder order = wmsReceiptOrderMapper.selectWmsReceiptOrderById(orderId);
            if (order != null)
            {
                int deleteDetailResult = wmsReceiptOrderMapper.deleteWmsReceiptOrderDetailByOrderNo(order.getOrderNo());
                if (deleteDetailResult < 0) {
                    throw new RuntimeException("删除订单明细失败");
                }
            }
        }
        return wmsReceiptOrderMapper.deleteWmsReceiptOrderByIds(orderIds);
    }

    /**
     * 删除收货订单信息
     * 
     * @param orderId 收货订单主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteWmsReceiptOrderById(Long orderId)
    {
        WmsReceiptOrder order = wmsReceiptOrderMapper.selectWmsReceiptOrderById(orderId);
        if (order != null)
        {
            int deleteDetailResult = wmsReceiptOrderMapper.deleteWmsReceiptOrderDetailByOrderNo(order.getOrderNo());
            if (deleteDetailResult < 0) {
                throw new RuntimeException("删除订单明细失败");
            }
        }
        return wmsReceiptOrderMapper.deleteWmsReceiptOrderById(orderId);
    }

    /**
     * 创建收货订单
     * 
     * @param wmsReceiptOrder 收货订单
     * @return 结果
     */
    @Override
    @Transactional
    public int createReceiptOrder(WmsReceiptOrder wmsReceiptOrder)
    {
        // 生成订单编号
        String orderNo = orderNumberRuleService.generateOrderNumber(wmsReceiptOrder.getOwnerId(), "RECEIPT");
        wmsReceiptOrder.setOrderNo(orderNo);
        wmsReceiptOrder.setStatus("PENDING");
        
        return insertWmsReceiptOrder(wmsReceiptOrder);
    }

    /**
     * 收货确认
     * 
     * @param order 收货订单对象（包含实收数量等信息）
     * @return 结果
     */
    @Override
    @Transactional
    public int confirmReceipt(WmsReceiptOrder order)
    {
        WmsReceiptOrder existingOrder = selectWmsReceiptOrderByOrderNo(order.getOrderNo());
        if (existingOrder == null || (!"PENDING".equals(existingOrder.getStatus()) && !"RECEIVING".equals(existingOrder.getStatus())))
        {
            return 0;
        }

        // 如果是第一次收货，更新订单状态为收货中
        int result = 1;
        if ("PENDING".equals(existingOrder.getStatus())) {
            existingOrder.setStatus("RECEIVING");
            existingOrder.setUpdateBy(SecurityUtils.getUsername());
            existingOrder.setUpdateTime(DateUtils.getNowDate());
            result = wmsReceiptOrderMapper.updateWmsReceiptOrder(existingOrder);
        }
        
        // 处理收货明细，更新实收数量并进行库存入库操作
        if (order.getDetailList() != null && !order.getDetailList().isEmpty())
        {
            // 先查询现有的明细数据
            List<WmsReceiptOrderDetail> existingDetails = wmsReceiptOrderDetailMapper.selectWmsReceiptOrderDetailByOrderNo(order.getOrderNo());
            
            for (WmsReceiptOrderDetail detail : order.getDetailList())
            {
                if (detail.getReceiptQty() != null && detail.getReceiptQty().compareTo(BigDecimal.ZERO) > 0)
                {
                    // 找到对应的现有明细记录
                    WmsReceiptOrderDetail existingDetail = existingDetails.stream()
                        .filter(d -> d.getItemId().equals(detail.getItemId()))
                        .findFirst().orElse(null);
                    
                    if (existingDetail != null)
                    {
                        // 累加实收数量
                        BigDecimal currentActualQty = existingDetail.getActualQty() != null ? existingDetail.getActualQty() : BigDecimal.ZERO;
                        BigDecimal newActualQty = currentActualQty.add(detail.getReceiptQty());
                        existingDetail.setActualQty(newActualQty);
                        
                        // 根据实收数量与预期数量比较设置行状态
                        if (newActualQty.compareTo(existingDetail.getExpectedQty()) >= 0) {
                            existingDetail.setLineStatus("COMPLETED");
                        } else {
                            existingDetail.setLineStatus("PARTIALLY_RECEIVED");
                        }
                        
                        existingDetail.setBatchNo(detail.getBatchNo());
                        existingDetail.setProductionDate(detail.getProductionDate());
                        existingDetail.setExpirationDate(detail.getExpirationDate());
                        existingDetail.setUpdateBy(SecurityUtils.getUsername());
                        existingDetail.setUpdateTime(DateUtils.getNowDate());
                        wmsReceiptOrderDetailMapper.updateWmsReceiptOrderDetail(existingDetail);
                        
                        // 调用商品库存增加API进行库存入库操作
                        InventoryIncreaseRequest increaseRequest = new InventoryIncreaseRequest();
                        increaseRequest.setTenantId(SecurityUtils.getTenantIdSafe());
                        increaseRequest.setOwnerId(existingOrder.getOwnerId());
                        increaseRequest.setWarehouseId(existingOrder.getWarehouseId());
                        increaseRequest.setItemId(existingDetail.getItemId());
                        increaseRequest.setSupplierId(existingOrder.getSupplierId());
                        increaseRequest.setBatchNo(existingDetail.getBatchNo());
                        increaseRequest.setProductionDate(existingDetail.getProductionDate());
                        increaseRequest.setExpirationDate(existingDetail.getExpirationDate());
                        increaseRequest.setIncreaseQty(detail.getReceiptQty());
                        increaseRequest.setUnit(existingDetail.getUnit());
                        increaseRequest.setInventoryStatus("NORMAL");
                        increaseRequest.setOperationType("RECEIPT");
                        // 处理库位信息
                        Long locationId = null;
                        if (StringUtils.isNotEmpty(detail.getRecommendedLocationCode())) {
                            // 根据库位编码查询库位信息
                            WmsLocation location = wmsLocationService.selectWmsLocationByCode(detail.getRecommendedLocationCode());
                            if (location == null) {
                                throw new RuntimeException("库位编码 " + detail.getRecommendedLocationCode() + " 不存在");
                            }
                            // 校验库位是否属于当前仓库
                            if (!location.getWarehouseId().equals(existingOrder.getWarehouseId())) {
                                throw new RuntimeException("库位编码 " + detail.getRecommendedLocationCode() + " 不属于当前仓库");
                            }
                            locationId = location.getId();
                        } else if (detail.getRecommendedLocationId() != null) {
                            // 兼容原有的推荐库位ID方式
                            locationId = detail.getRecommendedLocationId();
                        }
                        
                        if (locationId != null) {
                            increaseRequest.setLocationId(locationId);
                        }
                        increaseRequest.setDocumentType("RECEIPT_ORDER");
                        increaseRequest.setDocumentNo(existingOrder.getOrderNo());
                        increaseRequest.setReason("收货入库");
                        increaseRequest.setRemark("收货订单：" + existingOrder.getOrderNo() + "，商品：" + existingDetail.getItemId());
                        
                        // 调用商品库存增加API
                        InventoryIncreaseResponse response = wmsInventoryService.increaseInventory(increaseRequest);
                    }
                }
            }
            
            // 检查所有明细行是否都已完成收货，如果是则更新订单状态为COMPLETED
            List<WmsReceiptOrderDetail> allDetails = wmsReceiptOrderDetailMapper.selectWmsReceiptOrderDetailByOrderNo(order.getOrderNo());
            boolean allCompleted = allDetails.stream().allMatch(detail -> "COMPLETED".equals(detail.getLineStatus()));
            
            if (allCompleted) {
                existingOrder.setStatus("COMPLETED");
                existingOrder.setUpdateBy(SecurityUtils.getUsername());
                existingOrder.setUpdateTime(DateUtils.getNowDate());
                wmsReceiptOrderMapper.updateWmsReceiptOrder(existingOrder);
            }
        }
        
        return result;
    }

    /**
     * 取消收货订单
     * 
     * @param orderNo 订单编号
     * @return 结果
     */
    @Override
    @Transactional
    public int cancelReceiptOrder(String orderNo)
    {
        WmsReceiptOrder order = selectWmsReceiptOrderByOrderNo(orderNo);
        if (order == null || "COMPLETED".equals(order.getStatus()) || "CANCELLED".equals(order.getStatus()))
        {
            return 0;
        }

        // 更新订单状态为已取消
        order.setStatus("CANCELLED");
        order.setUpdateBy(SecurityUtils.getUsername());
        order.setUpdateTime(DateUtils.getNowDate());
        
        int result = wmsReceiptOrderMapper.updateWmsReceiptOrder(order);
        
        return result;
    }

    /**
     * 完成收货订单
     * 
     * @param orderNo 订单编号
     * @return 结果
     */
    @Override
    @Transactional
    public int completeReceiptOrder(String orderNo)
    {
        WmsReceiptOrder order = selectWmsReceiptOrderByOrderNo(orderNo);
        if (order == null || !"RECEIVING".equals(order.getStatus()))
        {
            return 0;
        }

        // 更新订单状态为已完成
        order.setStatus("COMPLETED");
        order.setUpdateBy(SecurityUtils.getUsername());
        order.setUpdateTime(DateUtils.getNowDate());
        
        int result = wmsReceiptOrderMapper.updateWmsReceiptOrder(order);
        
        return result;
    }

    /**
     * 新增收货订单明细信息
     * 
     * @param wmsReceiptOrder 收货订单对象
     */
    private void insertWmsReceiptOrderDetail(WmsReceiptOrder wmsReceiptOrder)
    {
        List<WmsReceiptOrderDetail> wmsReceiptOrderDetailList = wmsReceiptOrder.getDetailList();
        String orderNo = wmsReceiptOrder.getOrderNo();
        if (StringUtils.isNotNull(wmsReceiptOrderDetailList) && !wmsReceiptOrderDetailList.isEmpty())
        {
            // 批量校验商品编码并设置商品ID
            validateAndSetItemIds(wmsReceiptOrderDetailList);
            
            for (WmsReceiptOrderDetail wmsReceiptOrderDetail : wmsReceiptOrderDetailList)
            {
                // 验证必填字段
                if (wmsReceiptOrderDetail.getItemId() == null)
                {
                    throw new RuntimeException("商品ID不能为空");
                }
                // 验证预期数量必须大于0
                if (wmsReceiptOrderDetail.getExpectedQty() == null || wmsReceiptOrderDetail.getExpectedQty().compareTo(BigDecimal.ZERO) <= 0)
                {
                    throw new RuntimeException("预期数量必须大于0");
                }
                wmsReceiptOrderDetail.setOrderNo(orderNo);
                wmsReceiptOrderDetail.setCreateBy(SecurityUtils.getUsername());
                wmsReceiptOrderDetail.setCreateTime(DateUtils.getNowDate());
                if (StringUtils.isEmpty(wmsReceiptOrderDetail.getLineStatus()))
                {
                    wmsReceiptOrderDetail.setLineStatus("PENDING");
                }
            }
            
            // 调试日志：检查批量插入前的数据
            for (int i = 0; i < wmsReceiptOrderDetailList.size(); i++) {
                WmsReceiptOrderDetail detail = wmsReceiptOrderDetailList.get(i);
                if (detail.getItemId() == null) {
                    throw new RuntimeException("第" + (i + 1) + "行明细的商品ID为空");
                }
            }
            
            int batchResult = wmsReceiptOrderMapper.batchWmsReceiptOrderDetail(wmsReceiptOrderDetailList);
            if (batchResult <= 0) {
                throw new RuntimeException("批量插入收货订单明细失败");
            }
        }
    }

    /**
     * 批量校验商品编码并设置商品ID
     * 
     * @param detailList 收货订单明细列表
     */
    private void validateAndSetItemIds(List<WmsReceiptOrderDetail> detailList)
    {
        List<String> invalidItemCodes = new ArrayList<>();
        
        for (WmsReceiptOrderDetail detail : detailList)
        {
            String itemCode = detail.getItemCode();
            if (StringUtils.isNotEmpty(itemCode))
            {
                // 根据商品编码查询商品信息
                WmsItem item = wmsItemService.selectWmsItemByCode(itemCode);
                if (item != null)
                {
                    // 校验通过，设置商品ID
                    detail.setItemId(item.getId());
                }
                else
                {
                    // 校验失败，记录错误的商品编码
                    invalidItemCodes.add(itemCode);
                }
            }
            else if (detail.getItemId() == null)
            {
                // 既没有商品编码也没有商品ID
                throw new RuntimeException("商品编码和商品ID不能同时为空");
            }
        }
        
        // 如果有校验失败的商品编码，抛出异常
        if (!invalidItemCodes.isEmpty())
        {
            String errorMessage = String.join("、", invalidItemCodes) + "商品代码错误";
            throw new RuntimeException(errorMessage);
        }
    }

 }